'use strict';

angular.module('afasApp')
  .controller('UsersCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {


    $scope.items = [];
    $scope.users = [];
    $scope.staffs = [];
    $scope.role_profiles = [];
    $scope.newItem = {};

    $scope.params = {
      'include': 'product,inventory'
    };

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('users', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.items = results.data;
      });
    }
    getResultsPage(1);

    $scope.openItem = function(){
      $scope.formAdd = true;

      Services.getItems('staffs', {'getall' : true})
      .then(function(results){
        $scope.staffs = results.data;
      });

      Services.getItems('role_profiles', {'getall' : true})
      .then(function(results){
        $scope.role_profiles = results.data;
      });
    }

    $scope.add = function(){

      Services.add('users', $scope.item)
      .then(function(results){
        $scope.item = {};
        $scope.formAdd = false;
        getResultsPage(1);
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      })

    }

    $scope.delete = function (item) {
      Services.delete('products', item);
    };
  }]).controller('UserCtrl', ['$scope', 'Users', '$location', '$stateParams', 'Sexes', function ($scope, Users, $location, $stateParams, Sexes) {

    $scope.currentUser = {};
    $scope.currentID = $stateParams.id;
    $scope.sexes = Sexes.getSexes();
    $scope.currentUser =Users.getUser($stateParams.id);

    $scope.updateUser = function () {
      Users.updateUser($scope.currentUser, $scope.currentID);
      $location.path( '/user/'+$scope.currentID );
    };

    //datepicker

    $scope.open = function($event) {
      $event.preventDefault();
      $event.stopPropagation();

      $scope.opened = true;
    };

    $scope.dateOptions = {
      formatYear: 'yy',
      startingDay: 1
    };

    $scope.initDate = new Date($scope.currentUser.Bod);
    $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[0];
  }]);